<template>
  <div class="app-container">
    <el-container style="height: 760px; border: 1px solid #eee">
      <el-main style="margin-right:30px; width: 70%">
        <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" style="width: 100%; min-height: 700px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="addData.title" style="width: 580px;" />
          </el-form-item>
          <tinymce-editor :init="editorConfig" v-model="addData.content"></tinymce-editor>
        </el-form>
      </el-main>
      <el-aside style="background-color: #ffffff; width: 30%;">
        <el-form ref="addFormOption" :rules="rules" :model="addData" label-position="left" label-width="70px" style="width: 100%;  padding-top: 62px;margin-left:10px;">
          <el-form-item label="摘要" prop="summary">
            <el-input
              type="textarea"
              placeholder="请输入摘要"
              v-model="addData.summary"
              maxlength="128"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-input
              placeholder="标签长度2-18个字符,最多4个标签，逗号隔开"
              v-model="addData.tags"
              maxlength="80"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="编辑" prop="user_id">
            <el-select
              v-model="addData.user_id"
              placeholder="请选择编辑"
              v-on:change="editorSelectChange"
            >
              <el-option value="" label="请选择编辑" key=""></el-option>
              <el-option
                v-for="item in editorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="category_id">
            <el-select
              v-model="addData.category_id"
              placeholder="请选择分类"
            >
              <el-option value="" label="请选择分类" key=""></el-option>
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.title_cn"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="评论" prop="comment_state">
            <el-radio-group v-model="addData.comment_state">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="封面图" prop="cover">
            <el-upload
              class="cover-uploader"
              :action="imageUploadUrl"
              :show-file-list="false"
              :data="{ type: 'cover' }"
              :headers="uploadHeader"
              :on-success="handleUploadCoverImageSuccess">
              <img v-if="imageCoverUrl" :src="imageCoverUrl" class="cover">
              <i v-else class="el-icon-plus cover-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div style="margin-top: 20px; margin-right:30px;float: right;">
          <el-button type="primary" @click="handleAddSubmit()">
            提交
          </el-button>
        </div>
      </el-aside>
    </el-container>
  </div>
</template>
<script>
import { nodeAdd, nodeDetail, nodeImageUpload } from '@/api/node'
import waves from '@/directive/waves'
import { getToken } from '@/utils/auth'
import { strLength } from '@/utils/common'
import Editor from '@tinymce/tinymce-vue'

export default {
  name: 'NodeAdd',
  components: { 'tinymce-editor': Editor },
  directives: { waves },
  data() {
    const checkTitle = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 标题不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 64 || strLen < 6) {
        return callback(new Error('对不起， 标题长度为6-64个字符,汉字为3个字符!'))
      } else {
        callback()
      }
    }
    const checkSummary = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 摘要不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 256 || strLen < 6) {
        return callback(new Error('对不起， 摘要长度为6-256个字符,汉字为3个字符!'))
      } else {
        callback()
      }
    }
    const checkTags = function(rule, value, callback) {
      if (!value) {
        callback()
        return
      }

      // 检测单个标签的长度
      const tags = value.split(',')
      for (let i = 0; i < tags.length; i++) {
        const strLen = strLength(tags[i])
        if (strLen > 18 || strLen < 6) {
          return callback(new Error('对不起， 单个标签长度为6-18个字符,汉字为3个字符!'))
        }
      }

      // 检测标签的字符构成
      const reg = /^[,_A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 标签只能包含汉字,数字,字母,下划线,逗号'))
      } else {
        callback()
      }
    }
    const checkUserId = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 编辑不能为空!'))
      }

      const reg = /^[1-9]+[0-9]*$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 编辑用户的ID选择不正确!'))
      } else {
        callback()
      }
    }
    const checkCategoryId = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 分类不能为空!'))
      }

      const reg = /^[1-9]+[0-9]*$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 分类的ID选择不正确!'))
      } else {
        callback()
      }
    }
    return {
      // 副文本配置
      editorConfig: {
        body_class: 'node_id',
        language: 'zh_CN',
        height: 500,
        plugins: 'image',
        toolbar: 'image',
        images_upload_url: '',
        images_upload_handler: function(blobInfo, success, failure) {
          const imageData = new FormData()
          imageData.append('file', blobInfo.blob(), blobInfo.filename())
          nodeImageUpload(imageData).then(res => {
            if (res.success) {
              success(res.data.file_url)
            }
          })
        }
      },
      imageCoverUrl: '',
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'content/node/imageUpload',
      currentAction: 'add',
      addData: {
        id: 0,
        title: '',
        content: '',
        category_id: '',
        user_id: '',
        summary: '',
        tags: '',
        image_cover: '',
        image_check_list: [],
        comment_state: 0
      },
      tmpSelectedPid: 0,
      editorOptions: [],
      categoryOptions: [],
      rules: {
        title: [{ validator: checkTitle, trigger: 'blur' }, { required: true, message: '需要填写标题', trigger: 'blur' }],
        tags: [{ validator: checkTags, trigger: 'blur' }],
        summary: [{ validator: checkSummary, trigger: 'blur' }, { required: true, message: '需要填写摘要', trigger: 'blur' }],
        user_id: [{ validator: checkUserId, trigger: 'blur' }, { required: true, message: '需要指定编辑人员', trigger: 'blur' }],
        category_id: [{ validator: checkCategoryId, trigger: 'blur' }, { required: true, message: '需要指定分类', trigger: 'blur' }],
        comment_state: [{ required: true, message: '需要选择是否可评论', trigger: 'blur' }],
        content: [{ required: true, message: '需要填写内容', trigger: 'blur' }]
      }
    }
  },
  computed: {
    uploadHeader() {
      return { Authorization: 'bearer ' + getToken() }
    }
  },
  created() {
    this.resetAddData()
    this.addData.Id = this.$route.params.id
    nodeDetail(this.addData.Id).then((response) => {
      if (response.success) {
        this.editorOptions = response.data.editor_option
        this.categoryOptions = response.data.category_options
        if (this.addData.Id > 0) {
          this.addData = response.data.item
          this.addData.category_id = this.addData.category_id + ''
          this.imageCoverUrl = response.data.item.image_cover_url
          this.tmpSelectedPid = this.addData.category_id
          this.editorSelectChange(this.addData.user_id)
        }
      }
    }).catch(err => {
      console.log(err)
    })
    this.$nextTick(() => {
      this.$refs['addForm'].clearValidate()
    })
  },
  methods: {
    resetAddData() {
      this.imageCoverUrl = ''
      this.addData = {
        id: 0,
        category_id: '',
        user_id: '',
        summary: '',
        title: '',
        tags: '',
        content: '',
        image_cover: '',
        image_check_list: [],
        comment_state: 0
      }
    },
    handleAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          if (this.addData.content === '') {
            this.$message({
              type: 'error',
              message: '对不起, 内容不能为空!!'
            })
            return
          }
          nodeAdd(this.addData).then((response) => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              setTimeout(() => {
                const view = this.$route
                this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
                })
                this.$router.push({ path: '/content/node/list' })
              }, 1 * 200)
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    editorSelectChange(item) {
      if (item !== '' && this.editor_category_options[item].length > 0) {
        this.selected_editor_category_options = this.editor_category_options[item]
      } else {
        this.selected_editor_category_options = []
      }
    },
    handleCategoryChange(item) {
      if (item.length > 0) {
        this.addData.category_id = item[item.length - 1]
      }
    },
    handleUploadCoverImageSuccess(res, file) {
      if (res.success) {
        this.addData.image_cover = res.data.file_name
        this.imageCoverUrl = URL.createObjectURL(file.raw)
      }
    }
  }
}
</script>
<style scoped>
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.cover {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
